var BG = chrome.extension.getBackgroundPage();

$(document).ready(function () {
	//alert("ready a");
	localizePage();
	refreshualist();
	$("#uaform").submit(submitUa);
});

var ualist = "";

function localizePage() {
    $("[i18n]:not(.i18n-replaced)").each(function () {
        $(this).html(translate($(this).attr("i18n")));
    });
}

function translate(messageID, args) {
    return chrome.i18n.getMessage(messageID, args);
}

function refreshualist() {
	ualist = "";
    //alert("refreshualist");
    BG.loadUserAgents(renderUaEditLine, displayEditableUserAgents);
}

// edit form
var uadelete = chrome.i18n.getMessage("uaDelete");
var uaedit = chrome.i18n.getMessage("uaEdit");
function renderUaEditLine(row) {
    var uastring = row.value.string;
    if (uastring != navigator.userAgent) {
        var ua = '\'' + row.value.string + '\'';
        var uaid = row.key;
        var name = row.value.name;
        var line = '<tr><td width="120px;">' + name + '</td><td>' + uastring + '</td><td><a class="deleteconfirm" data-uaid="'+uaid+'" href="#">' + uadelete + '</a></td>' +
                '<td><a class="editua" href="#" data-uaid="'+uaid+'">' + uaedit + '</a></td></tr>';
        ualist += line;
    }
}

// delete
function deleteConfirm(e) {
	//debugger;
	var key = e.target.getAttribute("data-uaid");
    var question = chrome.i18n.getMessage("uaConfirmDelete", key);
    var r = confirm(question);
    if (r) {
        deleteUa(key);
        return false;
    }
    return false;
}
function deleteUa(key) {
	//alert("deleting");
    //BG.log("deleteUa");
    BG.deleteUserAgent(key, refreshualist);
    return false;
}

// edit
function fillForm(useragent) {
    //BG.log("filling out edit form");
    var loaded = useragent;
    $("#uaform #uamode").val("update");
    $("#uaform #uaid").val(loaded.name);
    $("#uaform #uaname").val(loaded.name);
    $("#uaform #uastring").val(loaded.string);
    $("#uaform #uadescription").val(loaded.description);
}
function editUa(e) {
    //BG.log("editUa");
    var key = e.target.getAttribute("data-uaid");
    BG.loadUserAgent(key, fillForm);
    return false;
}

function resetform(){
	// fireEvent('resetform');
    $("#uaform :input[type='text']").val("");
    $("#uaform #uamode").val("create");
	return false;
}

function createSuccess() {
    resetform();
    refreshualist();
}

function updateSuccess() {
    resetform();
    refreshualist();
}

function submitUa(){
	var uaname = $("#uaname").val();
	var uastring = $("#uastring").val();
	var uadescription = $("#uadescription").val();
	var key = $("#uaid").val();
	var mode = $("#uamode").val();
	var useragent = {"name":uaname, "string":uastring, "description":uadescription};
	if (mode == 'create') {
		BG.addUserAgent(useragent, createSuccess);
	} else if (mode == 'update') {
		BG.updateUserAgent(key, useragent, updateSuccess);
	}
	return false;
}

// exporter
var uaExport = new Array();

function jsonBuilder(row) {
    uaExport.push(row.value);
}

function uaExporter() {
    var jex = JSON.stringify(uaExport).replace(new RegExp(' ', 'g'), "%20");
    var dlink = document.createElement("a");
    dlink.textContent = chrome.i18n.getMessage("exportDownloadReady");
    // todo add date
    dlink.download = "chromeuseragentselector-export.txt";
    dlink.href = "data:application/json," + jex;
    $("#downloadLink").html(dlink);
}

function exportUserAgents() {
    BG.loadUserAgents(jsonBuilder, uaExporter);
}

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0, f; f = files[i]; i++) {
        var reader = new FileReader();
        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                var res = e.target.result.replace("data:text/plain;base64,", "");
                var useragents = window.atob(res);
                chrome.extension.getBackgroundPage().importUserAgents(useragents);
            };
        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    }
    alert(chrome.i18n.getMessage("importOk"));
}

// main listing
function displayEditableUserAgents() {
    $("#ualist").html(ualist);

    $('#resetform').on('click', resetform);
    $('.deleteconfirm').on('click', deleteConfirm);
    $('.editua').on('click', editUa);
    $('#exportuseragents').on('click', exportUserAgents);
    $('#files').on('change', handleFileSelect);
}
